package com.jxd.user.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.jxd.context.BaseContext;
import com.jxd.user.domain.dto.UsersDto;
import com.jxd.user.domain.pojo.Users;
import com.jxd.user.domain.utils.Result;
import com.jxd.user.service.IUsersService;
import io.swagger.annotations.Api;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.FilterWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-06-06
 */
@RestController
@Api(tags = "用户管理")
@RequestMapping("/users")
@CrossOrigin
public class UsersController {
    @Autowired
    private IUsersService usersService;
@GetMapping("login")
    public Result load(UsersDto dto){
    return usersService.load(dto);
    }

    /*
    * 查询用户信息*/
    @GetMapping("/{id}")
    public Result getOne(@PathVariable("id") Integer id ){
    return  usersService.selectByID(id);
    }

    /*
    * 保存用户信息
    * @param dto
    * @return Result*/

    @GetMapping
    public Result saveByUser(UsersDto dto){
      return  usersService.save(dto);
    }
    /*
    * 修改用户信息
    * @param dto
    * @return Result*/
    @PutMapping
    public Result updateByUser(UsersDto dto){
        return usersService.compile(dto);
    }
    /*
    * 删除用户信息
    * @param dto
    * @return Result*/
    @DeleteMapping("/{id}")
    public Result deleteByUser(@PathVariable("id") Integer id){
        return usersService.removeByuser(id);
    }
    /*
    * easyExcel导出*/
    @GetMapping("/export")
    @CrossOrigin
    public void export(HttpServletResponse response) throws IOException {
        String fileName ="工.xlsx";
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(fileName);

        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(resourceAsStream)
                .excelType(ExcelTypeEnum.XLSX)
                .build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        List<Users> list = usersService.list();

excelWriter.fill(new FillWrapper("user", list), writeSheet);
        excelWriter.finish();
    }

}
